import 'package:flutter/material.dart';

import 'package:flutter_widgets_pc/resources/l10n/kq_intl.dart';
import 'package:flutter_widgets_pc/widgets/formItem/kq_numer_item_view.dart';

import '../../config/kq_global.dart';
import '../../resources/kq_images.dart';
import '../../resources/kq_theme_colors.dart';
import '../../theme/kq_theme_manager.dart';
import '../divider/kq_divider.dart';
import 'entity/kq_form_entity.dart';

/// 通用表单组件 - 动态添加 原因选择+数量
///
/// [ItemType.addNumber]
///
/// 左边删除图标 + 标题 + 选择原因 + 下拉图标 + 数量减按钮  + 数量输入框 + 数量加按钮 + 单位
///
/// 结合 KqFormEntity 使用
///
/// 标题：title
/// 选择提示：hint
/// 选择的显示值使用：valueForShow
/// 选择的提交值使用:valueForSubmit
/// 数字值使用：qty
///
/// @author 周卓
///
class KqAddNumberItemView extends StatefulWidget {
  /// 数据
  final KqFormEntity entity;

  /// 选择控件点击回调
  final Function(KqFormQtyEntity entity)? onQtyTap;

  const KqAddNumberItemView({Key? key, required this.entity, this.onQtyTap})
      : super(key: key);

  @override
  KqAddNumberItemViewState createState() => KqAddNumberItemViewState();
}

class KqAddNumberItemViewState extends State<KqAddNumberItemView> {
  @override
  void initState() {
    widget.entity.widgetState = this;
    if (widget.entity.extraData == null) {
      widget.entity.extraData = <KqFormQtyEntity>[];
      _addRow();
    }
    super.initState();
  }

  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    // 背景颜色
    var bgColor = widget.entity.backgroundColor ??
        KqThemeManager.getFormConfig().backgroundColor ??
        KqThemeColors.bgWhite;
    return Visibility(
      visible: widget.entity.visible,
      child: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              color: bgColor,
              padding: EdgeInsets.only(
                  right: widget.entity.paddingHorizontal ??
                      KqThemeManager.instance
                          .getConfig()
                          .formConfig
                          .paddingHorizontal ??
                      16),
              child: Row(
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(
                        top: widget.entity.paddingVertical ??
                            KqThemeManager.instance
                                .getConfig()
                                .formConfig
                                .paddingVertical ??
                            15,
                        bottom: widget.entity.paddingVertical ??
                            KqThemeManager.instance
                                .getConfig()
                                .formConfig
                                .paddingVertical ??
                            15),
                    padding: EdgeInsets.only(right: 8),
                    child: Row(
                      children: <Widget>[
                        ///是否必填
                        Container(
                          alignment: Alignment.centerRight,
                          width: widget.entity.paddingHorizontal ??
                              KqThemeManager.instance
                                  .getConfig()
                                  .formConfig
                                  .paddingHorizontal ??
                              16,
                          padding: EdgeInsets.only(right: 2),
                          child: Text(
                            "*",
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                fontSize: KqThemeManager.instance
                                        .getConfig()
                                        .formConfig
                                        .mustInputFontSize ??
                                    14,
                                color: widget.entity.mustInput &&
                                        widget.entity.editable
                                    ? KqThemeColors.textRed
                                    : KqThemeColors.bgTransparent),
                          ),
                        ),

                        ///标题
                        LimitedBox(
                          maxWidth: KqThemeManager.instance
                                  .getConfig()
                                  .formConfig
                                  .titleMaxWidth ??
                              200,
                          child: Text(
                            widget.entity.title,
                            maxLines: widget.entity.multiline ? null : 1,
                            overflow: widget.entity.multiline
                                ? null
                                : TextOverflow.ellipsis,
                            style: widget.entity.titleStyle ??
                                TextStyle(
                                    fontSize: KqThemeManager.instance
                                            .getConfig()
                                            .formConfig
                                            .titleFontSize ??
                                        16,
                                    color: widget.entity.titleColor ??
                                        KqThemeManager.getFormConfig()
                                            .titleTextColor ??
                                        KqThemeColors.text26),
                          ),
                        )
                      ],
                    ),
                  ),
                  Expanded(
                      child: Row(
                    children: [
                      Expanded(
                          child: Text(
                        '${KqIntl.currentResource.total}${widget.entity.extraData.length}${KqIntl.currentResource.bar}',
                        textAlign: TextAlign.start,
                        style: TextStyle(
                            fontSize: 14,
                            color: widget.entity.contentColor ??
                                KqThemeColors.text8C),
                      )),
                      InkWell(
                        onTap: () {
                          _addRow();
                        },
                        child: Container(
                            alignment: Alignment.centerRight,
                            height: 44,
                            child: Image.asset(
                              KqImages.commonIcXinzeng16Blue,
                              width: 16,
                              height: 16,
                              color: KqThemeManager.getCommonConfig()
                                  .mainLightColor,
                              package: KqGlobal.packageName,
                            )),
                      )
                    ],
                  ))
                ],
              ),
            ),
            const KqDivider(),
            Container(
                color: KqThemeColors.bgF4,
                child: ListView(
                  padding: EdgeInsets.zero,
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  children: _buildCell(),
                ))
          ],
        ),
      ),
    );
  }

  //添加行
  void _addRow() {
    setState(() {
      widget.entity.extraData.add(KqFormQtyEntity(
        title: widget.entity.subTitle,
        hint: widget.entity.hint,
        unit: widget.entity.unit,
        minQty: widget.entity.minQty,
        qty: widget.entity.qty,
        onRemove: (entity) => {_removeRow(entity)},
        onTap: (entity) => widget.entity.onQtyTap?.call(widget.entity, entity),
      ));
      //必填时，限制最少1条
      if (widget.entity.mustInput && widget.entity.extraData.length == 1) {
        widget.entity.extraData[0].removable = false;
      } else {
        for (var value in widget.entity.extraData) {
          value.removable = true;
        }
      }
    });
  }

  // 删除行
  void _removeRow(KqFormQtyEntity entity) {
    setState(() {
      widget.entity.extraData.remove(entity);
      //必填时，限制最少1条
      if (widget.entity.mustInput && widget.entity.extraData.length == 1) {
        widget.entity.extraData[0].removable = false;
      } else {
        for (var value in widget.entity.extraData) {
          value.removable = true;
        }
      }
    });
  }

  // 数量控件列表
  _buildCell() {
    if (widget.entity.extraData is List<KqFormQtyEntity>) {
      List<KqFormQtyEntity> data = widget.entity.extraData;
      return data.map((e) => KqNumberItemView(entity: e)).toList();
    }
    return [];
  }
}
